package com.homework.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.homework.service.NameService;
import com.homework.service.impl.NameServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/RollCall")
public class RollCallServlet extends BaseServlet {
    private final static NameService service = new NameServiceImpl();
    private List<String> nameList = null;
    private List<String> afterList = new ArrayList<>();

    public void beforeRollCall(HttpServletRequest req, HttpServletResponse resp) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            resp.getWriter().print(mapper.writeValueAsString(nameList));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void findAllName(HttpServletRequest req, HttpServletResponse resp) {
        nameList = service.findName();
        ObjectMapper mapper = new ObjectMapper();
        try {
            resp.getWriter().print(mapper.writeValueAsString(nameList));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void afterRollCall(HttpServletRequest req, HttpServletResponse resp) {
        int id = Integer.parseInt(req.getParameter("id"));
        if (nameList.size() > 0) {
            afterList.add(nameList.get(id));
            nameList.remove(id);
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            resp.getWriter().print(mapper.writeValueAsString(afterList));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void resetList(HttpServletRequest req, HttpServletResponse resp) {
        nameList.clear();
        nameList = service.findName();
        afterList.clear();
        try {
            resp.getWriter().write("ok");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
